import { unref, watch } from 'vue';

export function unrefElement(elRef) {
  const plain = unref(elRef);
  return plain?.$el ?? plain;
}
/**
 * 构建阈值比率数组
 * @return {*}
 */
function buildThresholdList() {
  let thresholds = [];
  let numSteps = 20;

  for (let i = 1.0; i <= numSteps; i++) {
    let ratio = i / numSteps;
    thresholds.push(ratio);
  }

  thresholds.push(0);
  return thresholds;
}

export default function useIntersectionObserver(target, callback, options = {}) {
  const { root, rootMargin = '0px', threshold = buildThresholdList() } = options;
  const isSupported = window && 'IntersectionObserver' in window;
  const stopWatch = watch(
    () => ({
      el: unrefElement(target),
      root: unrefElement(root),
    }),
    ({ el, root }) => {
      if (!el) return;
      const observer = new window.IntersectionObserver(callback, {
        root,
        rootMargin,
        threshold,
      });
      observer.observe(el);
    },
  );

  const stop = () => {
    // cleanup();
    disconnect();
    stopWatch();
  };

  return {
    isSupported,
    stop,
  };
}
